package com.xdxc.service.strategy.gradingstrategy;

import com.xdxc.annotation.GradingStrategyType;
import com.xdxc.emuns.QuestionType;
import com.xdxc.model.dto.CorrectAnswerDTO;
import com.xdxc.model.entity.GradingResult;
import com.xdxc.model.entity.TempUserAnswer;
import com.xdxc.model.enums.AutoGradeQuestionType;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;


@Component
@GradingStrategyType(AutoGradeQuestionType.MULTIPLE_CHOICE)
public class MultiChoiceGradingStrategy implements GradingStrategy {
    @Override
    public GradingResult grade(TempUserAnswer tempUserAnswer, CorrectAnswerDTO correctAnswerDTO) {
            // 1. 获取用户答案和正确答案
        Set<Long> selectedIds = new HashSet<>(tempUserAnswer.getAnswerIds());
            Set<String> correctAnswerSet =  Optional.ofNullable(correctAnswerDTO.getOptionIds())
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(String::valueOf)  // 确保所有 ID 是 String 类型
                    .collect(Collectors.toSet());

            // 2. 检查是否有错选（选了不在正确答案中的选项）
            boolean hasWrongSelection = !correctAnswerSet.containsAll(selectedIds);

            // 3. 计算得分
            BigDecimal score;
            boolean isCorrect;

            if (hasWrongSelection) {
                // 有错选，不得分
                score = BigDecimal.ZERO;
                isCorrect = false;
            } else {
                // 无错选，计算正确选项比例得分
                int correctSelectedCount = selectedIds.size();
                int totalCorrectCount = correctAnswerSet.size();

                // 计算原始得分
                double rawScore = correctAnswerDTO.getScore() * (double) correctSelectedCount / totalCorrectCount;

                // 应用特殊舍入规则
                double decimalPart = rawScore - Math.floor(rawScore);
                if (decimalPart > 0) {
                    if (decimalPart <= 0.5) {
                        rawScore = Math.floor(rawScore) + 0.5;
                    } else {
                        rawScore = Math.floor(rawScore) + 1.0;
                    }
                }

                score = BigDecimal.valueOf(rawScore);
                isCorrect = (correctSelectedCount == totalCorrectCount);
            }

        GradingResult gradingResult1 = new GradingResult();
        gradingResult1.setAnswerId(tempUserAnswer.getId());
        gradingResult1.setIsCorrect(isCorrect);
        gradingResult1.setQuestionType(QuestionType.getCodeByDesc(String.valueOf(tempUserAnswer.getAnswerType())));
        gradingResult1.setUserScore(score);
        gradingResult1.setPaperId(tempUserAnswer.getPaperId());
            // 4. 构建结果
            return gradingResult1;
        }
    }

